<?php
/**
 * Created by PhpStorm.
 * User: JHR
 * Date: 2018/9/25
 * Time: 16:12
 */
namespace app\demo\controller;
use think\Exception;
use think\facade\Db;
use think\exception\HttpResponseException;
use think\facade\Log;

class Base {

    protected $cmd;
    protected $controller;
    protected $userinfo;
    protected $host;
    private $start_time;

    public function __construct()
    {
        $this->start_time = microtime(true);
        $this->host = request()->scheme() . '://' . request()->host() . "/";
        // 控制器初始化
        $this->initialize();
    }

    public function initialize() {
        $this->controller = request()->controller();
        $this->cmd = request()->controller() . '/' . request()->action();
//        $this->needLogin();
    }

    private function needLogin() {
        // 无视token, 直接放行
        $allow = [];
        // 需要登录的 controller | action
        $need = [
            'User', 'Upload','Index'
        ];
        // 无需权限验证
        $noAuth = [

        ];

        if(in_array($this->cmd,$need) || in_array($this->controller,$need)) {
            // 需要登录, 需要token
            if(in_array($this->cmd,$allow)) {
                // 接口白名单放行
                return true;
            }
            $token = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
            if(!$token) {
                // 未传入token
                throw new HttpResponseException(ajax('请传入token',-6));
            }else {
                $whereToken = [
                    ['token','=',$token]
                ];
                $token_exist = Db::table('mp_token')->where($whereToken)->find();

                if(!$token_exist) {
                    // token不存在
                    throw new HttpResponseException(ajax('token无效',-3));
                }else {

                    // token存在, 但是已过期
                    if((time() - $token_exist['create_time']) > config('token_expires_time')) {
                        throw new HttpResponseException(ajax('token已过期',-3));
                    }
                    $this->userinfo = $token_exist;
                }
            }
            return true;
        }else {
            return true;
        }
    }

    public function __destruct()
    {
        $diff_time = sprintf("%.6f",microtime(true)-$this->start_time);
        Log::record("--------- 运行时间 ".$diff_time." 秒 ---------");
    }



}